import { getStorage, setStorage } from '../../bridge.js'

export const name = 'markdown编辑器'

const tabsStorageKey = 'markdown-doc-tabs'
const storageKey = 'markdown-doc'

const editorCache = {}
const initEditor = async (id, root) => {
  if (!editorCache[id]) {
    const { createOpenEditor, toolbarItems } = window.Doc
    const div = document.createElement('div')
    div.className = 'ne-doc-major-editor'
    div.dataset.id = id
    root.append(div)
    editorCache[id] = createOpenEditor(div, {
      input: {},
      image: {
        isCaptureImageURL() {
          return false
        },
      },
      toolbar: {
        agentConfig: {
          default: {
            items: [
              toolbarItems.cardSelect,
              '|',
              toolbarItems.undo,
              toolbarItems.redo,
              toolbarItems.formatPainter,
              toolbarItems.clearFormat,
              '|',
              toolbarItems.fontsize,
              toolbarItems.bold,
              toolbarItems.italic,
              toolbarItems.strikethrough,
              toolbarItems.underline,
              toolbarItems.mixedTextStyle,
              '|',
              toolbarItems.color,
              toolbarItems.bgColor,
              '|',
              toolbarItems.taskList,
              toolbarItems.link,
            ],
          },
          // table选区工具栏
          table: {
            items: [
              toolbarItems.cardSelect,
              '|',
              toolbarItems.undo,
              toolbarItems.redo,
              toolbarItems.formatPainter,
              toolbarItems.clearFormat,
              '|',
              toolbarItems.style,
              toolbarItems.fontsize,
              toolbarItems.bold,
              toolbarItems.italic,
              toolbarItems.strikethrough,
              toolbarItems.underline,
              toolbarItems.mixedTextStyle,
              '|',
              toolbarItems.color,
              toolbarItems.bgColor,
              toolbarItems.tableCellBgColor,
              toolbarItems.tableBorderVisible,
              '|',
              toolbarItems.alignment,
              toolbarItems.tableVerticalAlign,
              toolbarItems.tableMergeCell,
              '|',
              toolbarItems.unorderedList,
              toolbarItems.orderedList,
              toolbarItems.indent,
              toolbarItems.lineHeight,
              '|',
              toolbarItems.taskList,
              toolbarItems.link,
              toolbarItems.quote,
              toolbarItems.hr,
            ],
          },
        },
      },
    })

    // 处理链接跳转问题
    editorCache[id].on('visitLink', (url) => {
      window.open(url)
    })

    // 监听内容变动
    editorCache[id].on('contentchange', () => {
      console.warn(`${storageKey}-${id}`)
      setStorage(`${storageKey}-${id}`, editorCache[id].getDocument('text/lake'))
    })

    const cache = await getStorage(`${storageKey}-${id}`).catch(() => null)
    if (cache) {
      editorCache[id].setDocument('text/lake', cache)
    } else {
      editorCache[id].setDocument('text/lake', '<p></p>')
    }
  } else {
    root.querySelector(`[data-id="${id}"]`).style.display = 'block'
  }
  return root.querySelector(`[data-id="${id}"]`)
}

export const render = async ({ root }) => {
  root.innerHTML = `
    <div class="editors">
      <div class="editor-tabs-wrapper">
        <div class="editor-tabs" id="editor-tabs">
          <div
            class="editor-tab active"
            data-id="default"
          >default</div>
        </div>
        <button id="editor-tab-add" class="editor-tab-add">+</button>
      </div>
      <div id="editor-container"></div>
    </div>
  `
  const tabs = root.querySelector('#editor-tabs')
  const container = root.querySelector('#editor-container')
  const addTabBtn = root.querySelector('#editor-tab-add')
  let currentEditorContainer = await initEditor('default', container)
  let tabsList = (await getStorage(tabsStorageKey).catch(() => [])) || []
  tabsList.forEach((tab) => {
    const tabItem = document.createElement('div')
    tabItem.className = 'editor-tab'
    tabItem.dataset.id = tab
    tabItem.textContent = tab
    tabs.append(tabItem)
  })

  addTabBtn.addEventListener('click', () => {
    const name = window.prompt('请输入文档名称')
    if (name) {
      const tabItem = document.createElement('div')
      tabItem.className = 'editor-tab'
      tabItem.dataset.id = name
      tabItem.textContent = name
      tabs.append(tabItem)
      setStorage(tabsStorageKey, [...tabsList, name])
    }
  })

  const allTabs = tabs.querySelectorAll('.editor-tab')
  allTabs.forEach(async (tab) => {
    tab.addEventListener('click', async (e) => {
      allTabs.forEach((tab) => {
        tab.classList.remove('active')
      })
      e.target.classList.add('active')
      currentEditorContainer.style.display = 'none'
      currentEditorContainer = await initEditor(e.target.dataset.id, container)
    })

    tab.addEventListener('contextmenu', (e) => {
      e.preventDefault()
      e.stopPropagation()
      if (window.confirm('确定删除该文档吗？')) {
      console.warn(tabsList, e.target.dataset.id)
        tabsList = tabsList.filter((tab) => tab !== e.target.dataset.id)
        setStorage(tabsStorageKey, tabsList)
        tab.remove()
      }
    })
  })
}

export const unmount = () => {
  Object.values(editorCache).forEach((editor) => {
    editor.destroy()
  })
}
